package com.pyl.admin.core.thymeleaf.utility;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.poi.ss.formula.functions.T;

import com.github.pagehelper.PageInfo;

import cn.hutool.core.util.ObjectUtil;

/**
 * 分类显示辅助工具对象
 *
 * @author 灵魂贰婶
 * @date 2018/8/14
 */
public class PageUtil {

	private String paramHref;

	/**
	 * 判断是否可开启分页
	 * 
	 * @param page
	 * @param request
	 * @return
	 */
	public boolean pageInit(PageInfo<T> page, HttpServletRequest request) {
		if (ObjectUtil.isNotNull(page) && page.getTotal() > page.getSize() && page.getPageNum() != 0) {
			// 获取分页参数地址
			String servletPath = request.getServletPath();
			StringBuffer param = new StringBuffer(servletPath + "?");
			Enumeration<?> em = request.getParameterNames();
			while (em.hasMoreElements()) {
				String name = (String) em.nextElement();
				if (!name.equals("current")) {
					String value = request.getParameter(name);
					param.append(name + "=" + value + "&");
				}
			}
			this.paramHref = param.toString();
			return true;
		}
		return false;
	}

	/**
	 * 获取分页码
	 * 
	 * @param page
	 * @return
	 */
	public List<String> pageCode(PageInfo<T> page) {
		int number = page.getPageNum();
		int totalPages = page.getPages();
		int start = 0;
		int length = 7;
		int half = length % 2 == 0 ? length / 2 : length / 2 + 1;
		List<String> codeList = new ArrayList<>();

		if (totalPages > length && number > half) {
			start = number - half;
		}
		if (totalPages > length && number > totalPages - half) {
			start = totalPages - length;
		}
		for (int i = 1; i <= (totalPages > length ? length : totalPages); i++) {
			codeList.add(String.valueOf(i + start));
		}
		if (totalPages > length && number > half) {
			codeList.set(0, "1");
			codeList.set(1, "…");
		}
		if (totalPages > length && number < totalPages - (half - 1)) {
			codeList.set(length - 2, "…");
			codeList.set(length - 1, String.valueOf(totalPages));
		}
		return codeList;
	}

	/**
	 * 会员制
	 * 
	 * @param page
	 * @param pageCode
	 * @param className
	 * @return
	 */
	public String pageActive(PageInfo<T> page, String pageCode, String className) {
		int number = page.getPageNum();
		if (!pageCode.equals("…")) {
			if (number == Integer.valueOf(pageCode)) {
				return " " + className;
			}
		}
		return "";
	}

	/**
	 * 是否有前一页
	 * 
	 * @param page
	 * @return
	 */
	public boolean isPrevious(PageInfo<T> page) {
		return page.isHasPreviousPage();
	}

	/**
	 * 是否有后一页
	 * 
	 * @param page
	 * @return
	 */
	public boolean isNext(PageInfo<T> page) {
		return page.isHasNextPage();
	}

	/**
	 * 是否有省略页
	 * 
	 * @param pageCode
	 * @return
	 */
	public boolean isCode(String pageCode) {
		return pageCode.equals("…");
	}

	/**
	 * 页面链接
	 * 
	 * @param pageCode
	 * @return
	 */
	public String pageHref(String pageCode) {
		return paramHref + "current=" + pageCode;
	}
}
